<template>
  <div class="user-after-sale">
    <div class="page-header">
      <h2>我的售后</h2>
      <el-button type="primary" @click="showApplyForm">申请售后</el-button>
    </div>

    <!-- 售后申请列表 -->
    <el-card class="list-card" v-loading="loading">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="全部" name="ALL"></el-tab-pane>
        <el-tab-pane label="处理中" name="PENDING"></el-tab-pane>
        <el-tab-pane label="已通过" name="APPROVED"></el-tab-pane>
        <el-tab-pane label="已拒绝" name="REJECTED"></el-tab-pane>
        <el-tab-pane label="已关闭" name="CLOSED"></el-tab-pane>
      </el-tabs>

      <div v-if="afterSaleList.length === 0" class="empty-state">
        <el-empty description="暂无售后申请记录"></el-empty>
      </div>

      <div v-else class="after-sale-list">
        <el-card v-for="item in afterSaleList" :key="item.id" class="after-sale-item">
          <div class="item-header">
            <div class="left">
              <span class="after-sale-no">售后单号: {{ item.afterSaleNo }}</span>
              <span class="order-no">订单号: {{ item.orderNo }}</span>
            </div>
            <div class="right">
              <el-tag :type="getStatusType(item.status)">{{ getStatusText(item.status) }}</el-tag>
            </div>
          </div>

          <div class="item-content">
            <div class="goods-info" v-for="goods in item.items" :key="goods.id">
              <el-image :src="goods.image" class="goods-image"></el-image>
              <div class="goods-detail">
                <div class="goods-name">{{ goods.itemName }}</div>
                <div class="goods-spec">{{ goods.specs || '默认规格' }}</div>
                <div class="goods-price">¥{{ formatPrice(goods.price) }} × {{ goods.quantity }}</div>
              </div>
            </div>
          </div>

          <div class="item-footer">
            <div class="apply-info">
              <span>申请时间: {{ formatDate(item.createTime) }}</span>
              <span>申请类型: {{ getTypeText(item.type) }}</span>
            </div>
            <div class="actions">
              <el-button type="primary" link @click="viewDetail(item.id)">查看详情</el-button>
              <el-button 
                v-if="item.status === 'PENDING'" 
                type="danger" 
                link 
                @click="cancelAfterSale(item.id)"
              >取消申请</el-button>
            </div>
          </div>
        </el-card>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
      </div>
    </el-card>

    <!-- 申请售后表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="申请售后"
      width="650px"
      :before-close="handleDialogClose"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="选择订单" prop="orderId">
          <el-select 
            v-model="form.orderId" 
            placeholder="请选择订单" 
            filterable 
            @change="handleOrderChange"
            style="width: 100%"
          >
            <el-option
              v-for="order in orderList"
              :key="order.id"
              :label="`订单号: ${order.orderNo} (${formatDate(order.createTime)})`"
              :value="order.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择商品" prop="items" v-if="form.orderId">
          <el-checkbox-group v-model="form.items">
            <div v-for="item in selectedOrderItems" :key="item.id" class="goods-checkbox-item">
              <el-checkbox :label="item.id">
                <div class="goods-info-small">
                  <el-image :src="item.image" class="goods-image-small"></el-image>
                  <div class="goods-detail-small">
                    <div class="goods-name-small">{{ item.name }}</div>
                    <div class="goods-spec-small">{{ item.specs || '默认规格' }}</div>
                    <div class="goods-price-small">¥{{ formatPrice(item.price) }} × {{ item.quantity }}</div>
                  </div>
                </div>
              </el-checkbox>
            </div>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="售后类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="REFUND">仅退款</el-radio>
            <el-radio label="RETURN">退货退款</el-radio>
            <el-radio label="EXCHANGE">换货</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="售后原因" prop="reason">
          <el-select v-model="form.reason" placeholder="请选择售后原因" style="width: 100%">
            <el-option label="商品质量问题" value="商品质量问题"></el-option>
            <el-option label="商品损坏" value="商品损坏"></el-option>
            <el-option label="商品与描述不符" value="商品与描述不符"></el-option>
            <el-option label="发货错误" value="发货错误"></el-option>
            <el-option label="多拍/错拍" value="多拍/错拍"></el-option>
            <el-option label="其他原因" value="其他原因"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="问题描述" prop="description">
          <el-input
            type="textarea"
            v-model="form.description"
            placeholder="请详细描述您遇到的问题"
            :rows="4"
          ></el-input>
        </el-form-item>

        <el-form-item label="上传凭证">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleImageChange"
            :on-remove="handleImageRemove"
            :limit="5"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">
            <p>最多上传5张图片，每张不超过5MB</p>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAfterSale" :loading="submitting">提交申请</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import service from '@/utils/request'

const router = useRouter()
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const activeTab = ref('ALL')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const afterSaleList = ref([])
const orderList = ref([])
const selectedOrderItems = ref([])
const fileList = ref([])

// 表单数据
const form = reactive({
  orderId: '',
  items: [],
  type: 'REFUND',
  reason: '',
  description: '',
  images: []
})

// 表单验证规则
const rules = {
  orderId: [{ required: true, message: '请选择订单', trigger: 'change' }],
  items: [{ type: 'array', required: true, message: '请至少选择一个商品', trigger: 'change' }],
  type: [{ required: true, message: '请选择售后类型', trigger: 'change' }],
  reason: [{ required: true, message: '请选择售后原因', trigger: 'change' }],
  description: [{ required: true, message: '请填写问题描述', trigger: 'blur' }]
}

// 获取售后列表
const getAfterSaleList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      status: activeTab.value === 'ALL' ? undefined : activeTab.value
    }
    
    const res = await service.get('/user/after_sale', { params })
    if (res) {
      afterSaleList.value = res.list || []
      total.value = res.total || 0
    }
  } catch (error) {
    console.error('获取售后列表失败:', error)
    ElMessage.error('获取售后列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取订单列表（用于申请售后）
const getOrderList = async () => {
  try {
    const res = await service.get('/user/orders', { 
      params: { 
        page: 1, 
        pageSize: 50,
        status: 'COMPLETED' // 只获取已完成的订单
      } 
    })
    if (res) {
      orderList.value = res.list || []
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败，请稍后重试')
  }
}

// 处理订单选择变化
const handleOrderChange = async (orderId) => {
  if (!orderId) {
    selectedOrderItems.value = []
    form.items = []
    return
  }
  
  try {
    const res = await service.get(`/user/orders/${orderId}`)
    if (res && res.items) {
      selectedOrderItems.value = res.items.map(item => ({
        id: item.id,
        name: item.itemName,
        image: item.image,
        specs: item.specs,
        price: item.price,
        quantity: item.quantity
      }))
    }
  } catch (error) {
    console.error('获取订单商品失败:', error)
    ElMessage.error('获取订单商品失败，请稍后重试')
  }
}

// 处理图片上传变化
const handleImageChange = (file) => {
  fileList.value.push(file)
}

// 处理图片移除
const handleImageRemove = (file) => {
  const index = fileList.value.indexOf(file)
  if (index !== -1) {
    fileList.value.splice(index, 1)
  }
}

// 提交售后申请
const submitAfterSale = async () => {
  const formRef = ref(null)
  
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    // 先上传图片
    const uploadedImages = []
    if (fileList.value.length > 0) {
      for (const file of fileList.value) {
        const formData = new FormData()
        formData.append('file', file.raw)
        
        const uploadRes = await service.post('/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        
        if (uploadRes && uploadRes.url) {
          uploadedImages.push(uploadRes.url)
        }
      }
    }
    
    // 提交售后申请
    const afterSaleData = {
      orderId: form.orderId,
      itemIds: form.items,
      type: form.type,
      reason: form.reason,
      description: form.description,
      images: uploadedImages
    }
    
    await service.post('/user/after_sale', afterSaleData)
    
    ElMessage.success('售后申请提交成功')
    dialogVisible.value = false
    resetForm()
    getAfterSaleList() // 刷新列表
    
  } catch (error) {
    console.error('提交售后申请失败:', error)
    ElMessage.error('提交售后申请失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

// 查看售后详情
const viewDetail = (id) => {
  router.push({
    name: 'UserAfterSaleDetail',
    params: { id }
  })
}

// 取消售后申请
const cancelAfterSale = async (id) => {
  try {
    await ElMessageBox.confirm('确认取消此售后申请？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await service.post(`/user/after_sale/${id}/cancel`)
    ElMessage.success('售后申请已取消')
    getAfterSaleList() // 刷新列表
  } catch (error) {
    if (error === 'cancel') return
    console.error('取消售后申请失败:', error)
    ElMessage.error('取消售后申请失败，请稍后重试')
  }
}

// 显示申请表单
const showApplyForm = () => {
  dialogVisible.value = true
  getOrderList()
}

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    orderId: '',
    items: [],
    type: 'REFUND',
    reason: '',
    description: '',
    images: []
  })
  selectedOrderItems.value = []
  fileList.value = []
}

// 处理标签页切换
const handleTabChange = () => {
  currentPage.value = 1
  getAfterSaleList()
}

// 处理每页数量变化
const handleSizeChange = (val) => {
  pageSize.value = val
  getAfterSaleList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getAfterSaleList()
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'PENDING': 'warning',
    'APPROVED': 'success',
    'REJECTED': 'danger',
    'CLOSED': 'info'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'PENDING': '处理中',
    'APPROVED': '已通过',
    'REJECTED': '已拒绝',
    'CLOSED': '已关闭'
  }
  return textMap[status] || '未知状态'
}

// 获取售后类型文本
const getTypeText = (type) => {
  const textMap = {
    'REFUND': '仅退款',
    'EXCHANGE': '换货',
    'RETURN': '退货退款'
  }
  return textMap[type] || '未知类型'
}

// 格式化价格
const formatPrice = (price) => {
  return Number(price).toFixed(2)
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '暂无'
  try {
    const d = new Date(date)
    return d.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (error) {
    return '日期格式错误'
  }
}

onMounted(() => {
  getAfterSaleList()
})
</script>

<style scoped>
.user-after-sale {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 20px;
  margin: 0;
  color: var(--text-regular);
}

.list-card {
  margin-bottom: 20px;
}

.empty-state {
  padding: 40px 0;
}

.after-sale-list {
  margin-top: 20px;
}

.after-sale-item {
  margin-bottom: 15px;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.item-header .left {
  display: flex;
  gap: 20px;
}

.after-sale-no, .order-no {
  color: var(--text-secondary);
  font-size: 14px;
}

.item-content {
  padding: 15px 0;
}

.goods-info {
  display: flex;
  margin-bottom: 10px;
}

.goods-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 15px;
}

.goods-detail {
  flex: 1;
}

.goods-name {
  font-size: 14px;
  color: var(--text-regular);
  margin-bottom: 5px;
}

.goods-spec {
  font-size: 12px;
  color: var(--text-secondary);
  margin-bottom: 5px;
}

.goods-price {
  font-size: 14px;
  color: var(--primary-color);
}

.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
}

.apply-info {
  display: flex;
  gap: 20px;
  color: var(--text-secondary);
  font-size: 14px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 申请售后表单样式 */
.goods-checkbox-item {
  margin-bottom: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}

.goods-info-small {
  display: flex;
  align-items: center;
  margin-left: 10px;
}

.goods-image-small {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 10px;
}

.goods-name-small {
  font-size: 14px;
  color: var(--text-regular);
  margin-bottom: 3px;
}

.goods-spec-small {
  font-size: 12px;
  color: var(--text-secondary);
  margin-bottom: 3px;
}

.goods-price-small {
  font-size: 12px;
  color: var(--primary-color);
}

.upload-tip {
  color: var(--text-secondary);
  font-size: 12px;
  margin-top: 5px;
}
</style> 